package com.fingard.dsp.bank.directbank.lcbip01;

import java.io.File;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.text.StringHelper;
import com.fingard.util.PdfGenerateUtil;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * @author marlon
 * @date 2018/9/10
 */
public class LCBIP01Receipt extends LCBIP01Base implements IReceipt {
    //交易传入的数据
    private String receiptSaveToMainDir = "";

    @Override
    public RetAtsReceipt qryReceipt(final ReqQryReceipt p_reqReceipt) throws Exception {
        //余额查询返回ATS的对象
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
        if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
            if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptPushServerUrl)) {
                    download(p_reqReceipt);
                    retAts.respCode = "0";
                    retAts.respInfo = "后台处理中";
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "DSPSystem未配置回单文件推送地址";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "DSPSystem未配置回单文件共享目录";
            }
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = "DSPSystem未配置回单文件下载保存主目录";
        }
        retAts.writeRetToATS();
        return retAts;
    }

    public void download(ReqQryReceipt p_reqReceipt) {
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());
            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            StringBuilder json = new StringBuilder();
            json.append("transType=downloadreceipt&data={\"rows\":[");
            LCBIP01Header bankHeader = new LCBIP01Header();
            bankHeader.TuxName = "QueryBankSlip";
            int count = 0;
            while (tmpIntFrom <= tmpIntTo) {
                Date fromDateStep = tmpCalendarFrom.getTime();
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));

                List<String> slipTypeList = getSlipTypes(p_reqReceipt.actNum);
                for (String slipTypes : slipTypeList) {
                    //发银行报文的XML对象
                    XmlTextWriter xmlWriter = new XmlTextWriter();
                    //写入通用的头部节点
                    bankHeader.ReqSeqNo = getQryTransID();
                    writeCommonHeader(xmlWriter, bankHeader);
                    xmlWriter.writeElementClosed("ReqReserved1");
                    xmlWriter.writeElementClosed("ReqReserved2");
                    xmlWriter.writeElementClosed("ReqReserved3");
                    xmlWriter.writeElementClosed("ReqReserved4");
                    xmlWriter.writeEndElement();

                    xmlWriter.writeStartElement("body");
                    xmlWriter.writeElementString("CustCode", bankFront.org);//客户编号
                    xmlWriter.writeElementString("SlipType", slipTypes);//回单类型
                    xmlWriter.writeElementString("AccNo", p_reqReceipt.actNum);//账户
                    xmlWriter.writeElementString("StartDate", Format.Date8Format.format(fromDateStep));//截至日期
                    xmlWriter.writeElementString("EndDate", Format.Date8Format.format(fromDateStep));//截至日期
                    xmlWriter.writeElementClosed("ReqReserved1");
                    xmlWriter.writeElementClosed("ReqReserved2");
                    xmlWriter.writeElementClosed("ReqReserved3");
                    xmlWriter.writeElementClosed("ReqReserved4");
                    xmlWriter.writeEndElement();
                    xmlWriter.writeEndElement();

                    //WriteBankLogLn("发送银行报文：" + xmlWriter.toXmlString());
                    String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String respCode = tmpBkReader.getFirstText("/lcbank/head/RespCode");
                            String respInfo = tmpBkReader.getFirstText("/lcbank/head/RespInfo");
                            if ("0".equals(respCode)) {
                                while (tmpBkReader.read("/lcbank/body/Bill")) {
                                    String bankSeqNo = tmpBkReader.readedXElement.getSingleText("BankSeqNo");
                                    String slipType = tmpBkReader.readedXElement.getSingleText("SlipType");
                                    String transDate = tmpBkReader.readedXElement.getSingleText("TransDate");
                                    String slipContent = tmpBkReader.readedXElement.getSingleText("SlipContent");
                                    String receiptFileName = p_reqReceipt.actNum + "_" + Format.Date8Format.format(fromDateStep) + "_" + bankSeqNo + ".pdf";
                                    String newFilePath = Format.Date8Format.format(new Date());
                                    String newPDFPath = this.getTempFileDirectory() + File.separator + p_reqReceipt.actNum + File.separator + receiptFileName;
                                    newFilePath = newFilePath.substring(0, 6) + "/" + newFilePath.substring(6, 8) + "/" + reqHeader.bankCode + "/" + p_reqReceipt.actNum + "/";
                                    WriteBankLogLn("开始解压文件" + newPDFPath + "至文件夹");
                                    String returnStr = "false";
                                    if (!StringHelper.isNullOrEmpty(slipContent)) {
                                        returnStr = PdfGenerateUtil.base64StringToPDF(newPDFPath, slipContent);
                                    } else {
                                        WriteBankLogLn("账户为" + p_reqReceipt.actNum + "银行流水号为" + bankSeqNo + "的电子回单内容为：" + slipContent);
                                    }
                                    if ("true".equals(returnStr)) {
                                        int result = -1;
                                        if (new File(newPDFPath).exists()) {
                                            result = SmbFileUtil.smbUploading(newPDFPath, newFilePath, FGBiz.dspCenter.dspSet.receiptShareDir);
                                        }
                                        if (result == 0 || result == 1) {
                                            if (result == 0) {
                                                WriteBankLogLn("文件上传成功");
                                            } else {
                                                WriteBankLogLn("文件已存在共享目录无需重复上传");
                                            }
                                            count++;
                                            //推送数据给ATS处理
                                            json.append("{");
                                            json.append("\"actNum\":\"" + p_reqReceipt.actNum + "\",");
                                            json.append("\"actCur\":\"" + p_reqReceipt.actCur + "\",");
                                            json.append("\"receiptCode\":\"" + bankSeqNo + "\",");
                                            json.append("\"receiptType\":\"" + "" + "\",");
                                            json.append("\"receiptState\":\"" + "" + "\",");
                                            json.append("\"oppActName\":\"" + "" + "\",");
                                            json.append("\"oppActNum\":\"" + "" + "\",");
                                            json.append("\"moneyway\":\"" + "" + "\",");
                                            json.append("\"amount\":\"" + "" + "\",");
                                            json.append("\"tranSeqNo\":\"" + reqHeader.transSeqID + "\",");
                                            json.append("\"tranCode\":\"" + "" + "\",");//交易码?
                                            json.append("\"tranDate\":\"" + Format.Date10Format.format(Format.Date8Format.parse(transDate)) + "\",");
                                            json.append("\"filePath\":\"" + newFilePath + receiptFileName + "\",");
                                            json.append("\"fileType\":\"1\"");
                                            json.append("},");
                                        } else {
                                            retAts.respCode = "-1";
                                            retAts.respInfo = "上传文件至共享目录失败，请检查共享目录配置是否正确";
                                            break;
                                        }
                                    } else {
                                        WriteBankLogLn("解压文件" + newPDFPath + "至文件夹失败,原因：" + returnStr);
                                    }
                                }
                            } else {
                                WriteBankLogLn(respInfo);
                            }
                        } else {
                            WriteBankLogLn(tmpSbMsg.toString());
                        }
                    } else {
                        WriteBankLogLn(tmpStrRet[1]);
                    }
                }
            }
            json.append("]}");
            WriteBankLogLn("账户" + p_reqReceipt.actNum + "上传成功电子回单笔数" + count);
            if (com.fingard.text.StringHelper.isNullOrEmpty(retAts.respCode) && json.toString().contains("receiptCode")) {
                String[] data = sendToATS(json.toString());
                WriteBankLogLn(json.toString());
                if (data[0].length() == 0 && "ok".equals(data[1])) {
                    retAts.respCode = "0";
                    retAts.respInfo = "推送数据到ATS成功,请查看数据";
                    WriteBankLogLn("推送数据到ATS成功,请查看数据" + json.toString());
                } else {
                    retAts.respCode = "0";
                    retAts.respInfo = "推送数据到ATS失败";
                    WriteBankLogLn("推送数据到ATS失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            WriteBankLogLn(e);
        }
        retAts.writeRetToATS();
    }


    private List<String> getSlipTypes(String actNum) throws Exception {
        String slipTypes = getBankConfig().getMapValueByKey("slipTypeMapping", actNum);
        if (StringHelper.isNullOrEmpty(slipTypes)) {
            slipTypes = getBankConfig().getMapValueByKey("slipTypeMapping", "*");
        }
        return Arrays.asList(slipTypes.split(","));
    }
}
